package com.berchen.controller;

import com.berchen.common.KeyEnum;
import com.berchen.common.busidb.model.UserVo;
import com.berchen.common.busidb.service.UserService;
import com.berchen.common.msm.service.MsmService;
import com.berchen.common.result.Result;
import com.berchen.common.result.ResultEnum;
import com.berchen.utils.Log4jUtils;
import com.berchen.utils.RandomUtil;
import com.berchen.utils.RedisUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("login/")
//@CrossOrigin(origins ="*",maxAge = 3600)
public class LoginController {

    private static Logger logger = Logger.getLogger(LoginController.class);

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private MsmService msmService;
    @Autowired
    private UserService userService;


    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        try {
            String code = (String) redisUtils.get(KeyEnum.USER_CODE.getKey() + phone);
            if (!StringUtils.isEmpty(code)) {
                return Result.ok();
            }
            code = RandomUtil.getSixBitRandom();
            // 发送验证码 并且 将验证码保存到redis中
            boolean isSend = msmService.send(phone, code);
            if (isSend) {
                redisUtils.set(KeyEnum.USER_CODE.getKey() + phone, code, 5, TimeUnit.MINUTES);
                return Result.ok();
            } else {
                return Result.set(ResultEnum.SUCCESS);
            }
        } catch (Exception e) {
            logger.error(Log4jUtils.getTrace(e));
            return Result.error();
        }
    }

    /**
     * 通过短信验证码进行登录 如果该账号不存在就创建账号
     *
     * @param phone
     * @param code
     * @return
     */
    @GetMapping("login/phone/{phone}/{code}")
    public Result loginPhone(@PathVariable String phone, @PathVariable String code) {

        try {
            if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
                return Result.set(ResultEnum.NO_PARAM);
            }
            // 验证code 是否正确
            String redisCode = (String) redisUtils.get(KeyEnum.USER_CODE.getKey() + phone);
            if (StringUtils.isEmpty(redisCode)) {
                return Result.set(ResultEnum.CODE_EXPIRED);
            }
            // 删除用户验证码
            redisUtils.del(KeyEnum.USER_CODE.getKey() + phone);
            UserVo userInfo=null;
            if (redisCode.equals(code)) {
                userInfo = userService.loginPhone(phone, code);
            }
            return Result.ok(userInfo);
        } catch (Exception e) {
            logger.error(Log4jUtils.getTrace(e));
            return Result.error();
        }
    }

    /**
     * 通过账号和密码进行登录
     *
     * @param account
     * @param password
     * @return
     */
    @GetMapping("login/account/{account}/{password}")
    public Result loginAccount(@PathVariable String account, @PathVariable String password) {
        try {
            if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
                return Result.set(ResultEnum.NO_PARAM);
            }
            UserVo userInfo= userService.loginAccount(account, password);
            if(userInfo==null){
                return Result.set(ResultEnum.UPLOAD_PASS_ERROR);
            }
            String token=userInfo.getToken();
            if (StringUtils.isEmpty(token)) {
                return Result.set(ResultEnum.ACCOUNT_NOT_EXIST);
            }
            return Result.ok(userInfo);
        } catch (Exception e) {
            logger.error(Log4jUtils.getTrace(e));
            return Result.error();
        }
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @DeleteMapping("logout/token")
    public Result logoutToken(HttpServletRequest request){
        try{
            String token=request.getHeader("token");
            if(StringUtils.isEmpty(token)){
                return Result.set(ResultEnum.NO_PARAM);
            }
            if(redisUtils.exists(KeyEnum.USER_TOKEN.getKey()+token)){
                redisUtils.getRedisTemplate().delete(KeyEnum.USER_TOKEN.getKey()+token);
            }
            return Result.ok();
        }catch (Exception e){
            logger.error(Log4jUtils.getTrace(e));
            return Result.error();
        }

    }

    /**
     * 通过token进行登录
     * @param token
     * @return
     */
    @GetMapping("login/token/{token}")
    public Result loginToken(@PathVariable String token){

        try{
            if(StringUtils.isEmpty(token)){
                return Result.set(ResultEnum.NO_PARAM);
            }
            String id= (String) redisUtils.get(KeyEnum.USER_TOKEN.getKey()+token);
            if(StringUtils.isEmpty(id)){
                return Result.set(ResultEnum.NO_LOGIN);
            }
            UserVo vo=new UserVo();
            vo.setId(Long.parseLong(id));
            UserVo userInfo = userService.getUserInfo(vo);
            return Result.ok(userInfo);
        }catch (Exception e){
            logger.error(Log4jUtils.getTrace(e));
            return Result.error();
        }

    }



}
